﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace DynamicViewFormLibrary
{
    /// <summary>
    /// RTF Dom Parser
    /// </summary>
    public class RtfDomParser
    {
        internal StringBuilder FormatTemplate(byte[] docBytes)
        {
            StringBuilder builder = new StringBuilder();
            string doc = Encoding.Default.GetString(docBytes);
            doc = doc.Substring(0, doc.LastIndexOf('}') - 1);
            builder.Append(doc);
            return builder;
        }

        internal StringBuilder FormatTemplate(string doc, string title)
        {
            StringBuilder builder = new StringBuilder();
            doc = doc.Substring(0, doc.LastIndexOf('}'));
            doc = doc.Replace("\\'bf\\'bc\\'ca\\'d4", "");
            doc = doc.Replace("\\'c3\\'fb\\'b3\\'c6", title);
            builder.Append(doc);
            return builder;
        }

        internal StringBuilder FormatTemplate(string doc)
        {
            StringBuilder builder = new StringBuilder();
            doc = doc.Substring(0, doc.LastIndexOf('}'));
            builder.Append(doc);
            return builder;
        }

        internal StringBuilder FormatContent(string doc)
        {
            StringBuilder builder = new StringBuilder();
            doc = doc.Substring(doc.LastIndexOf("\\viewkind4\\uc1"));
            doc = doc.Substring(0, doc.LastIndexOf('}'));
            doc = doc.Replace("\\f0", "\\f1");
            doc = doc.Replace("\\cf1 A", "\\cf12 A");
            doc = doc.Replace("\\cf1 B", "\\cf12 B");
            doc = doc.Replace("\\cf1 C", "\\cf12 C");
            doc = doc.Replace("\\cf1 D", "\\cf12 D");
            doc = doc.Replace("\\cf1 E", "\\cf12 E");
            doc = doc.Replace("\\cf1 F", "\\cf12 F");
            doc = doc.Replace("\\cf1 T", "\\cf12 T");
            builder.Append(doc);

            builder.Insert(0, "\\rtbtabs");
            builder.Append("\\rtbtabe");
            return builder;
        }

        internal List<string> SplitDoc(StringBuilder doc)
        {
            List<string> list = new List<string>();
            string pattern = @"(?<=(rtbtabs)).*?(?=(rtbtabe))";


            foreach (Match match in Regex.Matches(doc.ToString(), pattern))
                Console.WriteLine(match.Value);
            return list;
        }

    }
}
